package com.wayhome.srpingbootmybatis.placeCloud.controller;


import com.alibaba.fastjson.JSONObject;
import com.wayhome.srpingbootmybatis.config.ApiResult;
import com.wayhome.srpingbootmybatis.constant.PlaceCloudCfgConst;
import com.wayhome.srpingbootmybatis.placeCloud.dto.OrgCfgParam;
import com.wayhome.srpingbootmybatis.placeCloud.dto.OrgInfoParam;
import com.wayhome.srpingbootmybatis.placeCloud.dto.PlaceCloudBankCfg;
import com.wayhome.srpingbootmybatis.placeCloud.dto.PlaceCloudConf;
import com.wayhome.srpingbootmybatis.mapper.RegionalPlatformMapper;
import com.wayhome.srpingbootmybatis.utils.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/web/sendPlaceCloudConf")
public class SendPlaceCloudConfController {

    @Resource
    private RegionalPlatformMapper regionalPlatformMapper;

    @PostMapping(value = "/readExcelAndSendConfReq")
    public ApiResult<Boolean> readExcelAndSendConfReq(@RequestParam("file") MultipartFile file, @RequestParam(value = "source") String source) throws IOException, InvalidFormatException {
        InputStream inputStream = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        List<PlaceCloudConf> list = new ArrayList<>();
        for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (Objects.isNull(row)) {
                continue;
            }
            Cell cell = row.getCell(1);
            if (Objects.isNull(cell) || !CellType.STRING.equals(cell.getCellTypeEnum())) {
                continue;
            }
            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                continue;
            }


            String orgId = cell.getStringCellValue();
//         1:新增基础信息
            PlaceCloudConf placeCloudConf = genPlaceCloudConf(row);
            String result = sendCfg(placeCloudConf);
            System.out.println("==========新增基础信息=============：" + result);

//            2：默认配置改成OFFLINE
            String offlineDefaultCfg = executeOfflineDefaultCfg(orgId);
            System.out.println("################" + offlineDefaultCfg + "################");

//            3：新增银行外联配置
            String insertResult = executeInsertSql(source, orgId);
            System.out.println("+++++++++++++++++++新增银行外联配置：" +  insertResult + "++++++++++++++++");

        }
        String jsonString = JSONObject.toJSONString(list);
        return ApiResult.success(jsonString);
    }

    private String executeOfflineDefaultCfg(String orgId) {
        PlaceCloudBankCfg placeCloudBankCfg = new PlaceCloudBankCfg();
        placeCloudBankCfg.setOrgId(orgId);
        placeCloudBankCfg.setStatus(PlaceCloudCfgConst.STATUS_OFFLINE);
        placeCloudBankCfg.setPayChannel(PlaceCloudCfgConst.DEFAULT_PAY_CHANNEL);
        boolean result = regionalPlatformMapper.changeOutAccountStauts(placeCloudBankCfg);
        if (result) {
            return "success for OFFLINE alipay channel";
        } else {
            return "fail for OFFLINE alipay channel";
        }
    }

    private String executeInsertSql(String source, String orgId) {
        PlaceCloudBankCfg placeCloudBankCfg = new PlaceCloudBankCfg();
        placeCloudBankCfg.setOrgId(orgId);
        placeCloudBankCfg.setPayChannel("ABC");
        placeCloudBankCfg.setChannelName("农业银行");
        placeCloudBankCfg.setStatus(PlaceCloudCfgConst.STATUS_ONLINE);
        placeCloudBankCfg.setPayMode("INDIRECT");

        JSONObject configInfoJson = new JSONObject();
        String merchantId = "";
        if (PlaceCloudCfgConst.SHIYAO_SOURCE.equals(source)) {
            //石药
            merchantId = "103885035200067";
            String password = "Sydyf123";
            String filePath = "/home/zhifubaojianlian/abc/cert/shiyao.pfx";

            configInfoJson.put("merchantId", merchantId);
            configInfoJson.put("password", password);
            configInfoJson.put("filePath", filePath);


        } else if (PlaceCloudCfgConst.LERENTANG_SOURCE.equals(source)) {
            //乐仁堂
            merchantId = "103885030002698";
            String password = "123456";
            String filePath = "/home/zhifubaojianlian/abc/cert/lerentang.pfx";
            configInfoJson.put("merchantId", merchantId);
            configInfoJson.put("password", password);
            configInfoJson.put("filePath", filePath);
        }else if (PlaceCloudCfgConst.SHENWEI_SOURCE.equals(source)) {
            merchantId = "103885030002580";
            String password = "sw452827";
            String filePath = "/home/zhifubaojianlian/abc/cert/shenwei.pfx";
            configInfoJson.put("merchantId", merchantId);
            configInfoJson.put("password", password);
            configInfoJson.put("filePath", filePath);

        }

        placeCloudBankCfg.setExternalId(merchantId);
        placeCloudBankCfg.setConfigInfo(JSONObject.toJSONString(configInfoJson));
        boolean result = regionalPlatformMapper.insertOutAccount(placeCloudBankCfg);

        if (result) {
            return "success for insert";
        } else {
            return "fail for insert";
        }

    }


    private PlaceCloudConf genPlaceCloudConf(Row row) {

        PlaceCloudConf placeCloudConf = new PlaceCloudConf();

        OrgInfoParam orgInfoParam = new OrgInfoParam();
        String orgName = row.getCell(0).getStringCellValue();
        String orgId = row.getCell(1).getStringCellValue();
        String locInfo = row.getCell(2).getStringCellValue();

        String longitude = "";
        Cell cell3 = row.getCell(3);
        CellType cell3TypeEnum = cell3.getCellTypeEnum();
        if (CellType.NUMERIC.equals(cell3TypeEnum)) {
            longitude = String.valueOf(cell3.getNumericCellValue());
        } else {
            longitude = cell3.getStringCellValue();
        }

        String latitude = "";
        Cell cell4 = row.getCell(4);
        CellType cell4TypeEnum = cell4.getCellTypeEnum();
        if (CellType.NUMERIC.equals(cell4TypeEnum)) {
            latitude = String.valueOf(cell4.getNumericCellValue());
        } else {
            latitude = cell4.getStringCellValue();
        }

//        String province = row.getCell(16).getStringCellValue();
//        String city = row.getCell(17).getStringCellValue();
//        String state = row.getCell(18).getStringCellValue();
        String state = "";
        Cell cell18 = row.getCell(18);
        CellType cell18TypeEnum = cell18.getCellTypeEnum();
        if (CellType.NUMERIC.equals(cell18TypeEnum)) {
            int numericCellValue = (int) cell18.getNumericCellValue();
            state = String.valueOf(numericCellValue);
        } else {
            state = cell18.getStringCellValue();
        }
        String provinceName = row.getCell(19).getStringCellValue();
        String cityName = row.getCell(20).getStringCellValue();
        String stateName = row.getCell(21).getStringCellValue();

//        String orgLv = "";
//        Cell cell22 = row.getCell(22);
//        CellType cell22TypeEnum = cell22.getCellTypeEnum();
//        if (CellType.NUMERIC.equals(cell22TypeEnum)) {
//            orgLv = String.valueOf(cell22.getNumericCellValue());
//        }else {
//            orgLv = cell22.getStringCellValue();
//        }

//        String orgLvName = row.getCell(23).getStringCellValue();
        String poolarea = "";
        Cell cell24 = row.getCell(24);
        CellType cell24TypeEnum = cell24.getCellTypeEnum();
        if (CellType.NUMERIC.equals(cell24TypeEnum)) {
            int numericCellValue = (int) cell24.getNumericCellValue();
            poolarea = String.valueOf(numericCellValue);
        } else {
            poolarea = cell24.getStringCellValue();
        }

        orgInfoParam.setOrgId(orgId);
        orgInfoParam.setOrgCode(orgId);
        orgInfoParam.setOrgName(orgName);
        orgInfoParam.setLocInfo(locInfo);
        orgInfoParam.setLongitude(longitude);
        orgInfoParam.setLatitude(latitude);
//        orgInfoParam.setProvince(province);
//        orgInfoParam.setCity(city);
        orgInfoParam.setState(state);
        orgInfoParam.setProvinceName(provinceName);
        orgInfoParam.setCityName(cityName);
        orgInfoParam.setStateName(stateName);
//        orgInfoParam.setOrgLv(orgLv);
//        orgInfoParam.setOrgLvName(orgLvName);
        orgInfoParam.setPoolarea(poolarea);

        String orgChnlCrtfCode = row.getCell(10).getStringCellValue();
        OrgCfgParam orgCfgParam = new OrgCfgParam();
        orgCfgParam.setOrgChnlCrtfCode(orgChnlCrtfCode);

        placeCloudConf.setOrgCfgParam(orgCfgParam);
        placeCloudConf.setOrgInfoParam(orgInfoParam);

        return placeCloudConf;
    }


    private String sendCfg(PlaceCloudConf placeCloudConf) {
        try {
            String url = "https://pub.ylbzj.yhwch.com/ampminiapp/org/config/add";
            String param = JSONObject.toJSONString(placeCloudConf);
            return HttpUtil.doPostJson(url, param);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

}
